
use std::thread;
use std::sync::{Arc, mpsc, Mutex};
type Job = Box<dyn FnBox + Send + 'static>;
enum Message {
    NewJob(Job),
    Terminate,
}
trait FnBox {
    fn call_box(self: Box<Self>);
}
impl<F: FnOnce()> FnBox for F {
    fn call_box(self: Box<F>) {
        (*self)()
    }
}
pub struct ThreadPool {
    workers: Vec<Worker>,
    senders: mpsc::Sender<Message>,
}
// struct Job;
pub struct Worker {
    id:usize,
    thread: Option<thread::JoinHandle<()>>,
}
impl Worker {
    fn new(id: usize, receiver:Arc<Mutex<mpsc::Receiver<Message>>>) -> Worker {
        let thread = thread::spawn(move|| loop {
            let msg =receiver.lock().unwrap().recv().unwrap();
            match msg{
                Message::Terminate => {
                    println!("Worker {} was told to terminate.", id);
                    break;
                },
                Message::NewJob(job) => {
                    println!("Worker {} got a job; executing.", id);
                    // job();
                    job.call_box();
                }
            }
        });
        Worker { id, thread:Some(thread) }
    }
}
impl ThreadPool {
    /// Create a new ThreadPool.
    /// size: the number of threads in the pool
    /// #Panics
    /// the `new` function will panic if the size is zero.
    pub fn new(size: usize) -> ThreadPool {
        assert!(size > 0);
        let (sender, receiver) = mpsc::channel();
        let receiver = Arc::new(Mutex::new(receiver));
        let mut workers = Vec::with_capacity(size);
        for id in 0..size {
            //add new Worker to the pool
            workers.push(Worker::new(id, Arc::clone(&receiver)))
        }
        ThreadPool { workers, senders: sender }
    }
    pub fn execute<F>(&self, f: F) where F: FnOnce() + Send + 'static {
        let job = Box::new(f);
        self.senders.send(Message::NewJob(job)).unwrap();

    }
}
impl Drop for ThreadPool {
    fn drop(&mut self) {
        println!("Shutting down all workers.");
        for _ in &mut self.workers {
            self.senders.send(Message::Terminate).unwrap();
        }
        for worker in &mut self.workers {
            println!("Shutting down worker {}", worker.id);
            if let Some(thread) = worker.thread.take() {
                thread.join().unwrap();
            }
        }
    }
}
